package com.strongbj.iot.devices.dam.sub.dacai.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessage;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessageType;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnEntity;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 打开传感器设置界面的处理
 * 
 * @author yuzhantao
 *
 */
public class OpenSensorParamsPageHandle implements IMessageHandle<DaCaiMessage, Object> {
	private static Logger logger = LogManager.getLogger(OpenNetParamsPageHandle.class.getName());
	protected final static String COMMAND_CODE = "B111"; // 打开页面命令的编号
	protected final static byte GET_SENSOR_PARAMS_COMMAN = 0x17; // 获取传感器参数
//	protected final static String NET_PAGE_INDEX = "0004";  	// 网络设置页面的索引
	protected final static String DEFAULT_DEVICE_CODE = "000000"; // 设备默认编号
	protected final static byte[] EMPTY_DATAS = {}; // 空参数
	protected DAMMessageFactory damMessageFactory = new DAMMessageFactory();

	@Override
	public boolean isHandle(DaCaiMessage t) {
		if (t.getMessageType() == DaCaiMessageType.System && t.getCommand().equals(COMMAND_CODE)) {
			ScreenReturnEntity sr = ScreenReturnFactory.create(t.getDatas());
			// 如果点击触发的控件类型为按钮，屏幕id为0，按钮id为6，就认为是打开传感器设置界面
			if (sr.getControlType() == 16 && sr.getScreenId() == 0 && sr.getControlId() == 6)
				return true;
		}
		return false;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DaCaiMessage t) {
		Channel channel = ctx.channel();
		ITaskManager taskManager = DAMManager.getTaskManager(t.getDamCode());
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				if (channel != null && channel.isActive()) {
					// 发送获取DAM传感器参数的命令到DAM
					sendGetSensorParamsMessage(channel);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					logger.error("主机没有找到指定channel");
				}
			}
		});
		
		return null;
	}

	/**
	 * 发送获取本地网络的消息
	 * 
	 * @param channel
	 */
	private void sendGetSensorParamsMessage(Channel channel) {
		final byte[] datas = message2Bytes(DEFAULT_DEVICE_CODE, GET_SENSOR_PARAMS_COMMAN);
		ByteBuf bs = Unpooled.copiedBuffer(datas);
		ChannelFuture cf = channel.writeAndFlush(bs);
		cf.addListener(new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("DAM自动下发获取传感器参数命令成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("DAM自动下发获取传感器参数命令失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	/**
	 * 获取传感器命令转byte数组
	 * 
	 * @param np
	 * @return
	 */
	private byte[] message2Bytes(String deviceCode, byte command) {
		// 创建设置目标服务器的指令
		byte[] datas = damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()), deviceCode, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				command, // 命令
				EMPTY_DATAS // 空参数
		); // 通过dam消息工厂获取指令
		return datas;
	}
}
